<!DOCTYPE html>
<title>layout cruscotto</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<html>

	<link type="text/css" rel="stylesheet" href="css/leaflet.css" />
	<link type="text/css" rel="Stylesheet" href="css/bjqs.css" />
	<link type="text/css" rel="Stylesheet" href="css/jquery-ui.css" />
	
	<!--[if lte IE 8]>
	<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.6.4/leaflet.ie.css" />
	<![endif]-->
	<!--
	<script src="http://cdn.leafletjs.com/leaflet-0.6.4/leaflet.js"></script>
	<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
	-->

	<script src="js/leaflet.js"></script>
	<script src="js/jquery-1.9.1.min.js"></script>
	<script src="js/bjqs-1.3.min.js"></script>
	<script src="js/jquery.vticker.js"></script>
	<script src="js/jquery.scrollbox.js"></script>
	<script src="js/jquery-ui.js"></script>
	<script type="text/javascript" src="js/jquery.fullscreen-0.3.5.min.js"></script>
	
	<style>
		body {
			padding: 0;
			margin: 0;
		}
		html, body, #map {
			width: 100%;
			height: 100%;
		}
		.info {
			padding: 6px 8px;
			font: 14px/16px Arial, Helvetica, sans-serif;
			background: white;
			background: rgba(255,255,255,0.8);
			box-shadow: 0 0 15px rgba(0,0,0,0.2);
			border-radius: 5px;
		}
		.info h4 {
			margin: 0 0 5px;
			color: #777;
		}
		.legend {
			line-height: 18px;
			color: #555;
		}
		.legend i {
			width: 18px;
			height: 18px;
			float: left;
			margin-right: 8px;
			opacity: 0.7;
		}
		.lastupdate {
			background-color: #0E73B7; /* #FFFFFF;*/
			background-image: url("images/update.png");
			background-position: 5px 5px;
			background-repeat: no-repeat;
			border-radius: 8px;
			box-shadow: 0 1px 7px rgba(0, 0, 0, 0.4);
			clear: both;
			color: #FFFFFF;
			margin-top: 10px;
			margin-left: 10px;
			padding: 6px 6px 6px 30px;
			z-index: 7;
			opacity: 0.7;
		}

		/* NEWS */
		#newsDiv {
			width: 75%;
		}
		.news-box {
			overflow: hidden;
			width: 100%;
			height: 80px;
			background-color: rgba(14,115,183,0.8);
			border-radius: 8px;
			margin-bottom: 10px;
			margin-left: 10px; 
			/* margin: auto;  */
			display: inline-block;
			padding: 8px 8px 8px 8px;
		}
		.news {
			overflow: hidden;
			background-color: #0E73B7;
			width: 100%;
			height: 100%;
			margin-right: 10px;
			font: 24px Arial, Helvetica, sans-serif;
			background-image: url("images/stemma-vuoto.png");
			background-position: 15px 10px;
			background-repeat: no-repeat;
			background-size : 35px 60px;
			border-radius: 8px;
			box-shadow: 0 1px 7px rgba(0, 0, 0, 0.4);
			clear: both;
			color: #FFFFFF; /*#333333;*/
			/* padding: 5px 5px 5px 0px;*/ /* */
			z-index: 8;
			opacity: 0.9;
		}
		
		.news li {
			/* TODO allineare meglio testo verticalmente */
			vertical-align:middle; 
			padding: 25px 5px 5px 70px; 
			width: 100%;
		}
		
		/* EVENTI / ALERT */
		#eventsDiv {
			height: 96%;
			width: 22%;
		}
		.events-box {
			height: 94%; 
			/*width: 90%;*/
			overflow: hidden;
			background-color: rgba(14,115,183,0.8);
			background-image: url("images/stemma-vuoto.png");
			background-repeat: no-repeat;
			background-position: 10px 10px;
			background-size : 35px 60px;
			margin-top: 10px;
			margin-bottom: 10px;
			margin-right: 5px;
			margin-left: 5px;
			color: #FFFFFF;
			border-radius: 8px;
			padding: 10px 10px 10px 10px;
			z-index: 10;
		}
		.events-title {
			height: 80px; 
			font: 16px Arial, Helvetica, sans-serif;
			font-weight: bold;
			margin-left: 50px;
		}
		.events-title span {
			font: 14px Arial, Helvetica, sans-serif;
			margin-left: 5px;
			padding: 3px;
			border-radius: 8px;
			box-shadow: 0 1px 7px rgba(255, 255, 255, 0.4);
		}
		.events {
			overflow: hidden;
			height: 100%; 
			padding: 10px 10px 50px 10px;
			/* margin-top: 50px; */
			margin-bottom: 30px;
			opacity: 0.8;
			font: 14px Arial, Helvetica, sans-serif;
			background-color: #0E73B7;
			color: #FFFFFF;
			border-radius: 8px;
			box-shadow: 0 1px 7px rgba(0, 0, 0, 0.9);
			padding: 16px 16px 16px 16px;
			z-index: 11;
		}
		.events ul {
			overflow: hidden;
			list-style-type: none;
  			padding-top: 5px; padding-bottom: 5px;
			font-size: 0;
		}
		.events li {
			overflow: hidden;
			margin-top: 10px;
			width: 90%; 
			height:100%;
			/*height:250px; */
			font-size: 14px;
			border-bottom: 2px solid rgba(255,255,255,0.6); 
		}
		.title{
			font-weight: bold;
			font-size: 15px;
		}
		.icon{
			width: 25px;
			height: 25px;	
			margin-left:5px;
		}
		
		/* CONFIG */
		
		/*
		#area {
			width: 70px;
			height:70px;
			opacity: 0.8;
			background-color: #efefef;
		}
		.setup a {
			text-decoration: none;
			display: block;
		}
		.setup a span.gear {
			display: none;
			background: url('images/gear.png') center center no-repeat;
			background-size : 60px 60px;
			margin: 5;
			height: 60px;
			position: relative;
			z-index: 100;
			opacity: 0.8;
			filter: alpha(opacity=80);
		}
		#area:hover span.gear {
			display: block;
		}
		*/
		#dialog-form{
			display: none;
		}
		.dialog-form{
			overflow-y:scroll ;
			width: 100%;
		}
		.dialog-form .stemma {
			border-style: solid ;
			border-width: 1px;
			border-color: #BBBBBB;
			width: 60px;
			height: 60px;
			position:absolute;
			height:auto;
			left:560px;
			top: 30px;
		}
		.dialog-form label{
			display: inline-block;
			/*min-width: 100px;*/
			overflow: hidden;
		}
		.dialog-form input{
			float:right;
			width: 100%;
		}
		.dialog-form input.field-n{
			float:none;
			width: 150px;
		}
		.dialog-form input.field-t{
			float:none;
			width: 306px;
		}
		.dialog-form td{
			margin: 0;
			padding: 2px;
		}
		.table-news{
			width: 100%;
		}
		.table-news input{
			width: 90%;
		}
		
	</style>

	<body>

		<div id="map">
			<div id="newsDiv" class="leaflet-bottom">
				<div class="news-box" >
					<div class="news" id="banner-news">
						<ul class="bjqs">
							<!--
							<li>
								Lunedì 4/11/2013 ore 14:00 processione piazza mercato
							</li>
							<li>
								Domenica blocco del traffico dalle 9 alle 17
							</li>
							<li>
								Casello autastradale brescia est chiuso
							</li>
							<li>
								Sottopassaggio via calindri allagato
							</li>
							-->
						</ul>
					</div>
				</div>
			</div>
			<div id="eventsDiv" class="leaflet-top leaflet-right">
				<div class="events-box" id="box" >
					<div class="events-title">
						<div id="titolo" >Comune di ....</div><span>12:11</span>
					</div>
					<div id="events" class="events scroll-text" >
						<ul>
							<li>&nbsp;</li>
							<li>&nbsp;</li>
							<li>&nbsp;</li>
						</ul>
					</div>
				</div>
			</div>
			
			<div class="leaflet-top leaflet-left setup">
				<a  href="#" title="Setup"><span class="gear"> </span></a>
			</div>
		</div>

		<script>
		
			// GLOBALI
			var api_server_url = "http://osm.qmap.it";
			
			
			var api_server_url = "http://osm.qmap.it";
			var tile_server_url = "http://osm.qmap.it";

			var mapUrl = "http://{s}.tile.cloudmade.com/0FBA3CCBEEB240B8B396A762A558E0BB/999/256/{z}/{x}/{y}.png";

			
			
			function loadLayer(url, z_index) {
				var attribution = 'Map data &copy; OpenStreetMap contributors';
				z_index = typeof z_index !== 'undefined' ? z_index : 1;
				//alert(z_index);
				var layer = new L.TileLayer(url, {
					minZoom : 6,
					maxZoom : 16,
					attribution : attribution,
					zIndex : z_index,
					timestamp : new Date().getTime()
				});
				return layer;
			}

			function refreshLastUpdate() {
				var url = api_server_url + '/api/lastupdate';
				$.ajax({
					url : url,
					dataType : 'jsonp',
					success : function(json) {
						updateTimeDiv.html("<div class='lastupdate'>Ultimo aggiornamento: " + json.lastUpdate.substring(0, json.lastUpdate.length - 3) + "</div>");
						releaseId = json.releaseId;
						//updateTraffic(json.releaseId);
					},
					error : function(jqXHR, textStatus, errorThrown) {
						updateTimeDiv.html("Errore update");
					}
				});
			}
			
			function loadEvents(){
				var zoom = 10;
				//var url = api_server_url + '/api/events/' + zoom + '/' +"9.369621276855469,44.93029363624706,10.028800964355469,45.170177929417974";		
				var url = 'http://osm.qmap.it/api/events/11/9.039688110351562,44.82957822522573,10.358047485351562,45.27053750018046';
				$.ajax({
					url : url,
					dataType : 'jsonp',
					success : function(data) {
						// carica eventi	
						console.error("LEN:"+data.features.length);	
						console.error("URL:"+url);						
						var list = $("#events ul").empty();
						// TODO clear list per refresh				
                        $.each(data.features, function(i) {
                        	//console.error("dettaglio "+i);
                        	var e = data.features[i];								
						    var durl = api_server_url+"/api/event/"+e.properties.ogc_fid+"/"+e.properties.lcd_from+"/"+e.properties.lcd_to+"/"+e.properties.roa_lcd+"/"+e.properties.dir+".json";
						    dettaglioEvento(durl);							    
						});
						                        
					},
					error : function(jqXHR, textStatus, errorThrown) {
						console.error("ERROR loadEvents ");		
					}
				});
				
				$('#events').scrollbox({
				  linear: true,
				  step: 1,
				  delay: 0,
				  speed: 100
				});
			}
			
			function dettaglioEvento(url){
	                $.ajax({
	                    url : url,
	                    dataType : 'jsonp',
	                    type : 'GET',
	                    success : function(data) {
	                    	var list = $("#events ul");
	                    	var li = $('<li/>').appendTo(list);
	                    	var icon1 = "<img class='icon' src='"+api_server_url+"/api/eventicons/"+data.event_type_id+"' />" ;
	                    	var icon2 = data.cause_id!=""?"<img class='icon' src='"+api_server_url+"/api/eventicons/"+data.cause_id+"' />":"" ;
	                    	li.append("<p class='title'>"+data.event_name+"</p><span>"+icon1+icon2+"</span>"
	                    		+"<p>"+data.further_info+"</p>");
	                    },
	                    error : function(jqXHR, textStatus, errorThrown) {
	                        console.error("Errore nel caricamento dati dal server: " + errorThrown);
	                    }
	                });
               }
			
			function loadNews(){
			   $.get('data/news.txt', function(data) {
				   //alert(data);
				   //process text file line by line
				   var lines = data.split("\n");
				   //alert(lines);
				   for (var i = 0, len = lines.length; i < len; i++) {
	            		if(lines[i]!='')
	            			$('#banner-news ul').append("<li>"+lines[i]+"</li>");
	        		}
				   //$('#news').html(data.replace('\n','<br>'));
				}).fail(function() {
				    alert( "errore lettura file news" );
				}).always(function() {
				    $('#banner-news').bjqs({
					height : '100%', 
					width : '100%', 
					responsive : false,
					animspeed : 6000,
					showmarkers : false,
					showcontrols : false
				});
				});
			}
			
			var SetupCruscotto = L.Control.extend({
			    options: {
			        position: 'topleft'
			    },
			    onAdd: function (map) {
			        // create the control container with a particular class name
			        var container = L.DomUtil.create('div', ' leaflet-bar');
			        this._map = map;

					this._setupButton  = this._createButton(
					        "<img style='margin-top:2px' src='images/gear-mini.png' />", 
					        'Setup',  'setup',  container, this._setup,  this);
	
					//map.on('zoomend zoomlevelschange', this._updateDisabled, this);

			        return container;
			   },
			   _setup: function (e) {
					$('#zoom').val(map.getZoom());
					$('#lat').val(map.getCenter().lat.toFixed(8));
					$('#lng').val(map.getCenter().lng.toFixed(8));
					$('#stemma').val('');
					$( "#dialog-form" ).dialog( "open" );
				},
			  _createButton: function (html, title, className, container, fn, context) {
					var link = L.DomUtil.create('a', className, container);
					link.innerHTML = html;
					link.href = '#';
					link.title = title;
			
					var stop = L.DomEvent.stopPropagation;
			
					L.DomEvent
					    .on(link, 'click', stop)
					    .on(link, 'mousedown', stop)
					    .on(link, 'dblclick', stop)
					    .on(link, 'click', L.DomEvent.preventDefault)
					    .on(link, 'click', fn, context);
			
					return link;
				},
			});
			
			function Configurazione(){
				this.codice="";
				this.comune="";
				this.key="";
				this.stemma="";
				this.coordinate={lat:0,lng:0};
				this.zoom=0;
				this.news={};
			}
			
			function saveConfig(cfg) {
				var url = 'configurazione.php';
				var data = new FormData();
				data.append("codice",cfg.codice);
				data.append("config",JSON.stringify(cfg));
				data.append("stemma",$('#stemma')[0].files[0] );
				$.ajax({
					type: 'POST',
					url : url,
					data: data,
					cache: false,
				    contentType: false,
				    processData: false,
					success : function(data) {
						alert(data);
					},
					error : function(jqXHR, textStatus, errorThrown) {
						alert("jqXHR="+JSON.stringify(jqXHR));
					}
				});
			}
			
			var cfg = new Configurazione();
			
			function setupDialog(){
				 $( "#dialog-form" ).dialog({
					autoOpen: false,
					height: 500,
					width: 700,
					modal: true,
					buttons: {
						"Carica": function() {
							// CARICA
							$('#banner-news ul').empty();
							$.each($('#table-news tr input'), function( index, elem ) {
								var value = $(elem).val();
								//alert( index + ": " + value );
								$('#banner-news ul').append("<li>"+value+"</li>");
								$('#banner-news').bjqs({
							    	height : '100%',
									width : '100%',
									responsive : false,
									animspeed : 6000,
									showmarkers : false,
									showcontrols : false
								});
							});
							// MEMORIZZA FORM
							//$('body').fullscreen();
							$( this ).dialog( "close" );
						},
						"Salva": function() {
							var codice = $("#codice").val();
							if(codice=='') alert("Attenzione \n codice catastale \ non impostato !");
							else{
								// UPLOAD 
								//$('body').fullscreen();
								cfg.codice = $("#codice").val();
								cfg.comune = $("#comune").val();
								cfg.stemma = $("#stemma").val();
								if(cfg.stemma==""){
									alert(cfg.stemma);
									cfg.stemma="stemma-vuoto.png";
								}
								cfg.coordinate.lat = $("#lat").val();
								cfg.coordinate.lng = $("#lng").val();
								cfg.zoom = $("#zoom").val();
								cfg.news = [];
								$.each($('#table-news tr input'), function( index, elem ) {
									var value = $(elem).val();
									cfg.news.push(value);
								});
								//console.error( JSON.stringify(cfg));
								saveConfig(cfg);
								//$( this ).dialog( "close" );	
							}	
						},
						Cancel: function() {
							// RIPRISTINA FORM
							$( this ).dialog( "close" );
						}
						},
						close: function() {
							//
						}
					});
					$("#stemma").change(function(){
				        readImage(this, $('#stemma-img'));
				    });
				    $("#nuova").click(function(event){
				    	event.preventDefault();
				    	var nr = $('#table-news tr').length;
				    	$('#table-news tr:first').before("<tr id='row-"+(nr+1)+"'><td><button class='btn-del' id='btn-"+(nr+1)+
				    		"'>X</button><input class='ui-widget-content ui-corner-all' type='text' name='n-"+(nr+1)+"' value=''  ></td></tr>");
				    	refreshButtons();
				    });
				    $("#cerca").click(function(event){
				    	event.preventDefault();
				    	var codice = $("#codice").val();
						if(codice=='') alert("Attenzione \n codice catastale \ non impostato !");
						else {
							// cfg
							$.get('data/'+codice+'.json', function(data) {
								   var json = JSON.stringify(data);
								   cfg = JSON.parse(json);
								   //alert(JSON.stringify(cfg));
								   // posizione
								   $("#lat").val(cfg.coordinate.lat);
								   $("#lng").val(cfg.coordinate.lng);
								   $("#zoom").val(cfg.zoom);
								   // stemma
								   var imurl = "data/"+cfg.stemma;
								   readImage(imurl, $('#stemma-img'));
								   // comune
								   $("#titolo").text(cfg.comune);
								   $("#comune").val(cfg.comune);
								   $('.news').css("background-image","url(data/"+cfg.stemma+")");
								   $('.events-box ').css("background-image","url(data/"+cfg.stemma+")");	
								   // news
								   $('#table-news').empty();
								   for (var i = 0, len = cfg.news.length; i < len; i++) {
								   		$('#table-news').append("<tr id='row-"+i+"'><td><button class='btn-del' id='btn-"+i+
	    				    				"'>X</button><input class='ui-widget-content ui-corner-all' type='text' name='n-"+i+"' value='"+cfg.news[i]+"'  ></td></tr>");
								   }
								   refreshButtons();			   
								}).fail(function() {
								    alert( "errore lettura config" );
								}).always(function() {
								    
							});
						}
				    });
				    //refreshButtons();
			}
			
			function refreshButtons() {
				// refresh bottoni del news
				$(".btn-del").click(function(event){
				    event.preventDefault();
				    //alert("del");
				    var row = $(this).closest('tr');
				    row.remove();
				});
			}
			
			function readImage(input, img) {
				var id = img.attr('id');
		        if (input.files && input.files[0]) {
		            var reader = new FileReader();	            
		            reader.onload = function (e) {
		                $('#'+id).attr('src', e.target.result);
		            };	            
		            reader.readAsDataURL(input.files[0]);
		        }else { // url
        			$('#'+id).attr('src',input);
		        }
		    }
			
			var map;
			
			$(document).ready(function() {

				var mapLayer = loadLayer(mapUrl);
				map = L.map('map', {
					center: [45.050354,9.6990967] , // PC
					zoom : 11
				});
				map.addLayer(mapLayer);
				//loadEvents();
				loadNews();
				map.addControl(new SetupCruscotto());

				setupDialog();	
				
			});
		</script>


	
	<div id="dialog-form" class="dialog-form" title="Configurazione Cruscotto" >
		<form>
			<fieldset>
			<span ><img id="stemma-img" class="stemma" src = "images/stemma-vuoto.png"/></span>
			<table style="overflow-y:scroll ; width: 100%;">
				<tr><td>
					<label for="codice">Codice Catastale</label>
				</td><td>
					<input type="text" name="codice" id="codice" value="" class="field-n text ui-widget-content ui-corner-all">
					<button id="cerca">Cerca</button>
				</td></tr>
				<tr><td style="width: 200px">
					<label for="name">Comune</label>
				</td><td style="width: 600px">
					<input type="text" name="comune" id="comune" class="field-t text ui-widget-content ui-corner-all">
				</td></tr>
				<tr><td style="width: 200px">
					<label for="name">Stemma</label>
				</td><td style="width: 600px">
					<input type="file" name="stemma" id="stemma" class="field-t text ui-widget-content ui-corner-all">
				</td></tr>
				<!--
				<tr><td>
					<label for="chiave">Chiave Attivazione</label>
				</td><td>
					<input type="text" name="chiave" id="chiave" value="" class="field-t text ui-widget-content ui-corner-all">
				</td></tr>
				-->
				<tr>
					<td><label for="coordinate">Coordinate</label>
				</td><td>
					<input type="text" readonly name="lat" id="lat" value="" class="field-n">
					<input type="text" readonly name="lng" id="lng" value="" class="field-n">
				</td></tr>
				<tr><td>
					<label for="zoom">Zoom</label>
				</td><td>
					<input type="text" readonly name="zoom" id="zoom" value="" class="field-n ">
				</td></tr>
				<tr><td colspan="2">
					<table>
						<tr >
							<td><b>Elenco News</b>&nbsp;<button id="nuova">Nuova</button></td>
						</tr>
					</table>
					<table id="table-news" class="table-news" >
						<tr> </tr>
						<!--
						<tr >
							<td><button class="btn-del">X</button><input class="ui-widget-content ui-corner-all" type="text" name="n-1" value="Sottopassaggio via Calindri allagato " ></td>
						</tr>
						<tr>
							<td><button class="btn-del">X</button><input class="ui-widget-content ui-corner-all" type="text" name="n-2" value="Domenica blocco del traffico dalle 9 alle 17"></td>
						</tr>
						<tr>
							<td><button class="btn-del">X</button><input class="ui-widget-content ui-corner-all" type="text" name="n-3" value="Viale certosa chiuso per traffico"  ></td>
						</tr>
						<tr>
							<td><button class="btn-del">X</button><input class="ui-widget-content ui-corner-all" type="text" name="n-4"  value="Parata musicale in corso Garibaldi il 27/5/2013"  ></td>
						</tr>
						-->
					</table>
				</td></tr>
					
			</table>
			
			</fieldset>
			<input type="hidden" id="config" name="config" value="" />
			<input type="hidden" id="stamma-data" name="stemma-data" value="" />
		</form>
	</div>
</body>
	
</html>
